package com.itheima.auth.filter;

import com.itheima.pojo.UserInfo;
import com.itheima.support.SysConsts;
import com.itheima.utils.JwtTokenUtil;
import com.itheima.utils.RedisUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final String TOKEN_HEADER = "Authorization";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(TOKEN_HEADER) == null ? request.getParameter("token") : request.getHeader(TOKEN_HEADER);//获取前端传入的token
        try {
            if(token != null){
                //jwt解密，拿到当前登入用户名
                String username = JwtTokenUtil.parseToken(token);
                UserInfo userInfo = RedisUtil.get(SysConsts.USER_INFO_PREX_KEY + username);
                //模拟数据库查询
                User user = new User(username,userInfo.getPassword(), AuthorityUtils
                        .commaSeparatedStringToAuthorityList(userInfo.getAuthority()));

                //包装身份信息
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                //往下传递当前登入后的身份(数据保存在ThreadLocal中)
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            //放行,执行下一个过滤器
            filterChain.doFilter(request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
